<template>
  <div class="task-editor-container">
    <div class="editor-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <h1>{{ isEdit ? '编辑任务' : '创建任务' }}</h1>
      </div>
      <div class="header-right">
        <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
        <el-button type="primary" @click="submitTask" :loading="submitting">
          {{ isEdit ? '更新任务' : '创建任务' }}
        </el-button>
      </div>
    </div>

    <div class="editor-content">
      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="120px">
        <el-card title="基本信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务标题" prop="title">
                <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务类型" prop="type">
                <el-select v-model="taskForm.type" placeholder="选择任务类型" style="width: 100%">
                  <el-option label="学习任务" value="study" />
                  <el-option label="作业任务" value="homework" />
                  <el-option label="项目任务" value="project" />
                  <el-option label="考试任务" value="exam" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="taskForm.priority" placeholder="选择优先级" style="width: 100%">
                  <el-option label="低" value="low" />
                  <el-option label="中" value="medium" />
                  <el-option label="高" value="high" />
                  <el-option label="紧急" value="urgent" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="难度等级" prop="difficulty">
                <el-rate v-model="taskForm.difficulty" :max="5" show-text />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="任务描述" prop="description">
            <el-input
              v-model="taskForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入任务描述"
            />
          </el-form-item>
        </el-card>

        <el-card title="时间安排" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="taskForm.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止时间" prop="endTime">
                <el-date-picker
                  v-model="taskForm.endTime"
                  type="datetime"
                  placeholder="选择截止时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预计用时" prop="estimatedHours">
                <el-input-number
                  v-model="taskForm.estimatedHours"
                  :min="0.5"
                  :max="100"
                  :step="0.5"
                  placeholder="小时"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提醒设置" prop="reminderType">
                <el-select v-model="taskForm.reminderType" placeholder="选择提醒方式" style="width: 100%">
                  <el-option label="无提醒" value="none" />
                  <el-option label="开始前1小时" value="1hour" />
                  <el-option label="开始前1天" value="1day" />
                  <el-option label="开始前3天" value="3days" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card title="任务内容" style="margin-top: 20px">
          <el-form-item label="任务目标" prop="objectives">
            <div class="objectives-list">
              <div 
                v-for="(objective, index) in taskForm.objectives"
                :key="index"
                class="objective-item"
              >
                <el-input v-model="objective.content" placeholder="输入任务目标" />
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  @click="removeObjective(index)"
                  v-if="taskForm.objectives.length > 1"
                />
              </div>
              <el-button type="primary" icon="Plus" @click="addObjective">添加目标</el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="任务步骤" prop="steps">
            <div class="steps-list">
              <div 
                v-for="(step, index) in taskForm.steps"
                :key="index"
                class="step-item"
              >
                <span class="step-number">{{ index + 1 }}</span>
                <el-input v-model="step.content" placeholder="输入任务步骤" />
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  @click="removeStep(index)"
                  v-if="taskForm.steps.length > 1"
                />
              </div>
              <el-button type="primary" icon="Plus" @click="addStep">添加步骤</el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="相关资源" prop="resources">
            <div class="resources-list">
              <div 
                v-for="(resource, index) in taskForm.resources"
                :key="index"
                class="resource-item"
              >
                <el-input v-model="resource.name" placeholder="资源名称" style="width: 200px" />
                <el-input v-model="resource.url" placeholder="资源链接" style="flex: 1" />
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  @click="removeResource(index)"
                />
              </div>
              <el-button type="primary" icon="Plus" @click="addResource">添加资源</el-button>
            </div>
          </el-form-item>
        </el-card>

        <el-card title="其他设置" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="标签" prop="tags">
                <el-select
                  v-model="taskForm.tags"
                  multiple
                  filterable
                  allow-create
                  placeholder="选择或创建标签"
                  style="width: 100%"
                >
                  <el-option
                    v-for="tag in availableTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否公开" prop="isPublic">
                <el-switch
                  v-model="taskForm.isPublic"
                  active-text="公开"
                  inactive-text="私有"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备注" prop="notes">
            <el-input
              v-model="taskForm.notes"
              type="textarea"
              :rows="3"
              placeholder="任务备注信息"
            />
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getTaskDetail,
  createTask,
  updateTask,
  getTaskTags
} from '@/api/task'

const route = useRoute()
const router = useRouter()

// 响应式数据
const taskFormRef = ref()
const saving = ref(false)
const submitting = ref(false)
const availableTags = ref([])
const isEdit = ref(false)

// 表单数据
const taskForm = reactive({
  title: '',
  type: '',
  priority: 'medium',
  difficulty: 3,
  description: '',
  startTime: null,
  endTime: null,
  estimatedHours: 1,
  reminderType: 'none',
  objectives: [{ content: '' }],
  steps: [{ content: '' }],
  resources: [],
  tags: [],
  isPublic: false,
  notes: ''
})

// 表单验证规则
const taskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择截止时间', trigger: 'change' }
  ]
}

// 页面加载
onMounted(async () => {
  if (route.params.id) {
    isEdit.value = true
    await loadTask()
  }
  await loadTags()
})

// 加载任务详情
const loadTask = async () => {
  try {
    const response = await getTaskDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(taskForm, response.data)
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
  }
}

// 加载标签
const loadTags = async () => {
  try {
    const response = await getTaskTags()
    if (response.code === 200) {
      availableTags.value = response.data || []
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 添加目标
const addObjective = () => {
  taskForm.objectives.push({ content: '' })
}

// 删除目标
const removeObjective = (index) => {
  taskForm.objectives.splice(index, 1)
}

// 添加步骤
const addStep = () => {
  taskForm.steps.push({ content: '' })
}

// 删除步骤
const removeStep = (index) => {
  taskForm.steps.splice(index, 1)
}

// 添加资源
const addResource = () => {
  taskForm.resources.push({ name: '', url: '' })
}

// 删除资源
const removeResource = (index) => {
  taskForm.resources.splice(index, 1)
}

// 保存草稿
const saveDraft = async () => {
  try {
    saving.value = true
    // 这里可以调用保存草稿的API
    ElMessage.success('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败')
  } finally {
    saving.value = false
  }
}

// 提交任务
const submitTask = async () => {
  try {
    await taskFormRef.value.validate()
    submitting.value = true
    
    // 过滤空的目标和步骤
    const filteredObjectives = taskForm.objectives.filter(obj => obj.content.trim())
    const filteredSteps = taskForm.steps.filter(step => step.content.trim())
    const filteredResources = taskForm.resources.filter(res => res.name.trim() && res.url.trim())
    
    const submitData = {
      ...taskForm,
      objectives: filteredObjectives,
      steps: filteredSteps,
      resources: filteredResources
    }
    
    if (isEdit.value) {
      await updateTask(route.params.id, submitData)
      ElMessage.success('任务更新成功')
    } else {
      await createTask(submitData)
      ElMessage.success('任务创建成功')
    }
    
    router.push('/task/my-tasks')
  } catch (error) {
    console.error('提交任务失败:', error)
    ElMessage.error('提交任务失败')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.task-editor-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px 30px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.editor-content {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 20px;
}

.objectives-list,
.steps-list,
.resources-list {
  .objective-item,
  .step-item,
  .resource-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    
    .step-number {
      width: 24px;
      height: 24px;
      background-color: #409eff;
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
    }
  }
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    gap: 16px;
    padding: 16px 20px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .editor-content {
    padding: 20px 10px;
  }
  
  .objective-item,
  .step-item,
  .resource-item {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
